<template>
  <a-card class="task-tabs-card">
    <template #title>
      <div v-if="!disabled" class="flex items-center justify-between">
        <div style="line-height: 32px">
          是否需要表单：
          <a-radio-group
            v-model:value="isNeedForm"
            :disabled="taskInfo.taskType === taskTypeEnum.custom"
            @change="isNeedFormChange"
          >
            <a-radio :value="true">需要</a-radio>
            <a-radio :value="false" :disabled="disabledNoNeed">不需要</a-radio>
          </a-radio-group>
        </div>
        <div>
          <a-button v-if="isNeedForm" type="primary" @click="chooseFormTem">选择表单</a-button>
        </div>
      </div>
    </template>
    <formList
      v-if="isNeedForm"
      ref="formListRef"
      :task-id="taskInfo.taskId"
      :source-type="taskInfo.sourceType"
      :form-business-level="formBusinessLevel"
      :disabled="disabled"
    />
    <IcpEmpty v-else />
  </a-card>
  <selectFormTemplate
    ref="selectFormTemplateRef"
    :form-business-level="formBusinessLevel"
    :task-id="taskInfo.taskId"
    :template-type="isPharmacy() ? 1 : isConfig() ? 1 : 2"
    :app-id="appId"
    :has-search="hasSearch"
    @submit="handleSubmit"
    @show-empty="showEmpty"
  />
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import formList from './components/formList.vue'
import { isConfig, isPharmacy } from '@@/utils/index'
import { taskTypeEnum } from '@@/enums/taskEnum'

const props = defineProps<{
  taskInfo: any
  needForm: boolean | undefined
  isPublishUser: boolean
  formBusinessLevel?: Number
  disabled?: boolean
  hasSearch?: boolean
  appId?: string
  disabledNoNeed?: boolean
}>()
const isNeedForm = ref(props.needForm ? true : false)
const selectFormTemplateRef = ref()
const formListRef = ref()

const formBusinessLevel = computed(() => {
  if (isConfig()) {
    // 运维端
    return 1
  } else if (props.taskInfo.sourceType === 'progressTemplate') {
    // sop进度模板
    return 3
  }
  // 项目
  return 4
})

const emits = defineEmits(['resetData'])

const chooseFormTem = () => {
  console.log(selectFormTemplateRef, '---')
  selectFormTemplateRef.value.show()
}
const handleSubmit = () => {
  formListRef.value.reloadTable()
}
const isNeedFormChange = () => {
  const taskId = props.taskInfo.mainId || 'taskId'
  const required = props.taskInfo.isPerNeedForm || 'required'
  props.taskInfo
    .updateFormRequiredApi({
      [taskId]: props.taskInfo.taskId,
      [required]: isNeedForm.value
    })
    .then(() => {
      emits('resetData', isNeedForm.value)
    })
    .catch(() => {
      isNeedForm.value = props.needForm || false
    })
}

/**
 * 展示空白表单
 */
const showEmpty = () => {
  formListRef.value.showEmptyForm()
}
</script>

<style lang="less"></style>
